import { Controller } from 'egg';
import { Op } from 'sequelize';

export default class UserController extends Controller {
  public async login() {
    this.ctx.success({
      data: {
        status: 'ok',
        type: 'account',
        currentAuthority: 'admin',
      }
    })
  }

  public async getUser() {
    const { id } = this.ctx.state.user;
    const user = await this.ctx.model.AuthUser.findOne({
      attributes: [ 'id', 'username', 'email', 'type'],
      where: {
        id
      }
    });
    this.ctx.success({ data: user });
  }

  async moduleList() {
    const { user } = this.ctx.state;
    
    // 根据用户id查询用户所在的用户组，有可能有多个
    const groups = await this.ctx.model.AuthUserGroup.findAll({
      where: {
        user_id: user ? user.id : ''
      }
    });
    const module = await this.ctx.model.AuthGroupModule.findAll({
      where: {
        group_id: {
          [Op.in]: groups.map(it => it.group_id)
        }
      }
    });
    const list = module.map(it => it.module_id);
    // 获取功能模块
    const modules = await this.ctx.model.AuthModule.findAll(
      {
        where: {
          id: {
            [Op.in]: [...list],
          },
        }
      },
    );

    this.ctx.success({
      data: modules,
    });
  }


}
